﻿using System;
using UnityEngine;
using System.Collections;
using System.IO;
using System.Collections.Generic;
namespace Config
{
	using CxExtension;
	public class BaseArchive
	{
		public string id { get; set; }
		public string name { get; set; }
		public virtual string Key { get { return id; } }
		public void Parse(Dictionary<string,string> map)
		{
			OnParse(map);
			OnParseAfter();
		}
		public virtual void OnParseAfter()
		{

		}
		public static bool operator true(BaseArchive self)
		{
			return self != null;
		}
		public static bool operator false(BaseArchive self)
		{
			return self == null;
		}
		public virtual void OnParse(Dictionary<string,string> map)
		{
			this.SetValue(map);
			var key = this.Key;
			if(string.IsNullOrEmpty(key))
			{
				Debug.LogErrorFormat("[{0}]类配置id不能为null",GetType().Name);
				return;
			}
			//dataMap[key] = this;
		}
	}
	public class BaseArchive<T> : BaseArchive where T : BaseArchive
	{
		/// <summary>
		/// 如果文件不存在是否用默认的配置自动写入一个
		/// 默认 true
		/// </summary>
		private static bool autoWriteIfNotExit = true;
		public static string jsonPath = string.Empty;
		public static string JsonPath
		{
			get
			{
				if(string.IsNullOrEmpty(jsonPath))
				{
					var p = "";
					switch(Application.platform)
					{
						case RuntimePlatform.OSXEditor:
						case RuntimePlatform.OSXPlayer:
						case RuntimePlatform.WindowsPlayer:
						case RuntimePlatform.WindowsEditor:
							p = Path.GetDirectoryName(Application.dataPath);
							break;
						case RuntimePlatform.Android:
						case RuntimePlatform.IPhonePlayer:
							p = Application.persistentDataPath;
							break;
						default:
							break;
					}
					//var ps = Path.GetDirectoryName(p);
					var ps = string.Format("{0}/Config/Json",p);
					if(!Directory.Exists(ps))
					{
						Directory.CreateDirectory(ps);
					}
					jsonPath = ps;
				}
				return jsonPath;
			}
		}
		public static string GetFilePath(string file)
		{
			return string.Format("{0}/{1}.json",JsonPath,file);
		}
		public static string GetFileResoucesPath(string file)
		{
			return string.Format("Config/Json/{0}",file);
		}
		public static void SetAutoWriteSingle(bool value)
		{
			autoWriteIfNotExit = value;
		}
		public static bool SaveText(string file,string txt)
		{
			string fpath = GetFilePath(file);
			var fs = File.Open(fpath,FileMode.Create);
			var sw = new StreamWriter(fs);
			sw.Write(txt);
			sw.Flush();
			sw.Close();
			fs.Close();
			return true;
		}
		/// <summary>
		/// 从Json配置文件路径中读取数据
		/// </summary>
		/// <param name="file"></param>
		/// <returns></returns>
		public static string LoadText(string file)
		{
			string json = "";
			string filePath = GetFilePath(file);//Application.persistentDataPath + @"/MFMemoryFlopGameJson.mf";
			if(File.Exists(filePath))
			{
				//var finfo1 = new FileInfo(filePath);
				json = File.ReadAllText(filePath);
			}
			else
			{
				string rpath = GetFileResoucesPath(file);
				TextAsset t = Resources.Load<TextAsset>(rpath);
				if(t)
				{
					json = t.text;
					if(autoWriteIfNotExit)
					{
						File.WriteAllText(filePath,json);
					}
				}
				else
				{
					Debug.LogFormat("在{0} 中没有找到配置表",rpath);
				}
			}
			return json;
		}
		public static T LoadArchiveJson(string file)
		{
			string json = LoadText(file);
			T data = default(T);
			if(string.IsNullOrEmpty(json))
			{
				data = Activator.CreateInstance<T>();
				SaveArchiveJson(data,file);
			}
			else
			{
				data = JsonUtility.FromJson<T>(json);
			}
			return data;
		}
		public static T LoadArchiveJson()
		{
			return LoadArchiveJson(typeof(T).Name);
		}
		/// <summary>
		/// 存储一个对象为json文件
		/// </summary>
		/// <param name="self">对象实例</param>
		/// <param name="filename">json文件名称</param>
		/// <returns></returns>
		public static bool SaveArchiveJson(System.Object self,string filename)
		{
			var json = JsonUtility.ToJson(self);
			SaveText(filename,json);
			return true;
		}
		/// <summary>
		/// 把当前对象保存成为json文件
		/// </summary>
		/// <param name="fname">保存的文件名称</param>
		/// <returns></returns>
		public bool Save2Json(string fname)
		{
			return SaveArchiveJson(this,fname);
		}
		/// <summary>
		/// 把当前对象保存成为json文件 文件名称是 当前类的类名 即 this.GetType().Name
		/// </summary>
		/// <returns></returns>
		public bool Save2Json()
		{
			return Save2Json(this.GetType().Name);
		}
	}
}
